package com.boho.system.service;

/**
 * @File name:  UserService.java 
 * @Create on:  2010-05-10 19:30:171
 * @Author   :  陈伟
 *
 * @ChangeList
 * ---------------------------------------------------
 * Date         Editor              ChangeReasons
 *
 */

import java.sql.Connection;
import java.util.List;

import cn.boho.framework.context.ActionContext;
import cn.boho.framework.exception.UserOperationException;
import cn.boho.framework.log.Logger;
import cn.boho.framework.po.ComboPager;
import cn.boho.framework.po.DynaBeanMap;
import cn.boho.framework.po.POUtils;
import cn.boho.framework.po.Pager;
import cn.boho.framework.service.MessageService;

import com.boho.common.Constant;
import com.boho.common.SystemUtils;
import com.boho.system.dao.TSysUserDao;
import com.boho.system.po.TUserPO;


/**
 * 用户管理业务类
 * @author 陈伟
 *
 */
public class UserService {

	private static Logger logger = new Logger(org.apache.log4j.Logger.getLogger(UserService.class));
	
	/**
	 * 添加用户信息
	 * @param atx
	 * @param loginName
	 * @param username
	 * @param password
	 * @param phone
	 * @param email
	 * @param remark
	 * @return
	 * @throws Exception
	 */
	public static String addUser(ActionContext atx, String loginName, String username, String phone, String email, String remark) throws Exception{
		SystemUtils.getSessionUser(atx);
		Connection con = atx.getConection();
		//验证用户是否存在
		checkUserIsExist(atx,loginName);
		//添加用户信息
		TUserPO tSysUserPO = new TUserPO();
		StringBuffer userID = new StringBuffer();
		tSysUserPO.setLoginName(loginName);
		tSysUserPO.setPassword(Constant.DEFAULT_PASSWORD);
		tSysUserPO.setUserName(username);
		tSysUserPO.setPhone(phone);
		tSysUserPO.setEmail(email);
		tSysUserPO.setRemark(remark);
		POUtils.insert(con, tSysUserPO, userID);
		//日志
		StringBuffer info = new StringBuffer();
		info.append("\n【添加用户】")
			.append("\nIP："+atx.getRemoteAddr())
			.append("\n操作用户ID："+atx.getSessionValue(Constant.SESSION_USER_NO).toString())
			.append("\n"+tSysUserPO.toXMLStringBuffer().toString());
		logger.info(info.toString());
		return userID.toString();
	}
	
	/**
	 * 根据用户账号验证用户是否存在
	 * @param atx
	 * @param mobile
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static DynaBeanMap checkUserIsExist(ActionContext atx, String loginName) throws Exception{
		DynaBeanMap dbm = TSysUserDao.getUserByLoginName(atx.getConection(), loginName);
		if(dbm != null){
			UserOperationException uoe = new UserOperationException();
			atx.setErrorContext("FSTI_SYS_USER_1001", MessageService.getMessage("FSTI_SYS_USER_1001"),uoe);
		}
		return dbm;
	}
	
	/**
	 * 修改用户信息
	 * @param atx
	 * @param username
	 * @param usertype
	 * @param mobile
	 * @param phone
	 * @param area
	 * @param email
	 * @param remark
	 * @param userid
	 * @throws Exception
	 */
	public static void updateUserByPK(ActionContext atx, String username, String phone, String email, String remark, Integer userid) throws Exception{
		SystemUtils.getSessionUser(atx);
		Connection con = atx.getConection();
		TUserPO conditionTSysUserPO = new TUserPO();
		TUserPO valueTSysUserPO = new TUserPO();
		conditionTSysUserPO.setUserId(userid);
		valueTSysUserPO.setUserName(username);
		valueTSysUserPO.setPhone(phone);
		valueTSysUserPO.setEmail(email);
		valueTSysUserPO.setRemark(remark);
		POUtils.update(con, conditionTSysUserPO, valueTSysUserPO,false);
		//日志
		StringBuffer info = new StringBuffer();
		info.append("\n【修改用户】")
			.append("\nIP："+atx.getRemoteAddr())
			.append("\n操作用户ID："+atx.getSessionValue(Constant.SESSION_USER_NO).toString())
			.append("\n修改对象"+conditionTSysUserPO.getUserId())
			.append("\n修改内容："+valueTSysUserPO.toXMLStringBuffer().toString());
		logger.info(info.toString());
	}
	
	/**
	 * 修改SESSION用户信息
	 * @param atx
	 * @param username
	 * @param usertype
	 * @param mobile
	 * @param phone
	 * @param area
	 * @param email
	 * @param remark
	 * @param userid
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static void updateUserBySession(ActionContext atx, String username, String email, String remark, Integer userid) throws Exception{
		SystemUtils.getSessionUser(atx);
		Connection con = atx.getConection();
		TUserPO conditionTSysUserPO = new TUserPO();
		TUserPO valueTSysUserPO = new TUserPO();
		conditionTSysUserPO.setUserId(userid);
		valueTSysUserPO.setUserName(username);
		valueTSysUserPO.setEmail(email);
		valueTSysUserPO.setRemark(remark);
		POUtils.update(con, conditionTSysUserPO, valueTSysUserPO,false);
		
		DynaBeanMap dbmUser = TSysUserDao.getTSysUserByPk(con, userid);
		atx.setSessionValue(Constant.SESSION_USER_BEAN, dbmUser);
		//日志
		StringBuffer info = new StringBuffer();
		info.append("\n【修改登录用户信息】")
			.append("\nIP："+atx.getRemoteAddr())
			.append("\n操作用户ID："+atx.getSessionValue(Constant.SESSION_USER_NO).toString())
			.append("\n修改对象"+conditionTSysUserPO.getUserId())
			.append("\n修改内容："+valueTSysUserPO.toXMLStringBuffer().toString());
		logger.info(info.toString());
	}
	
	/**
	 * 根据用户ID修改用户密码
	 * @param atx
	 * @param userid
	 * @param oldPWD
	 * @param newPWD
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static void updateUserPWD(ActionContext atx, String oldPWD, String newPWD) throws Exception{
		String sessionId = SystemUtils.getSessionUser(atx);
		Integer userid = Integer.parseInt(sessionId);
		Connection con = atx.getConection();
		DynaBeanMap dbmUser = TSysUserDao.getUserPWDByPK(con, userid);
		if(dbmUser != null){
			String password = (String)dbmUser.get("PASSWORD");
			if(!password.equals(oldPWD)){
				UserOperationException uoe = new UserOperationException();
				atx.setErrorContext("FSTI_SYS_USER_1005", MessageService.getMessage("FSTI_SYS_USER_1005"), "【修改密码】", uoe);
				throw uoe;
			}
			else{
				TUserPO conditionTSysUserPO = new TUserPO();
				TUserPO valueTSysUserPO = new TUserPO();
				conditionTSysUserPO.setUserId(userid);
				valueTSysUserPO.setPassword(newPWD);
				POUtils.update(con, conditionTSysUserPO, valueTSysUserPO, false);
				
				//日志
				StringBuffer info = new StringBuffer();
				info.append("\n【修改用户密码】")
					.append("\nIP："+atx.getRemoteAddr())
					.append("\n操作用户ID："+atx.getSessionValue(Constant.SESSION_USER_NO).toString())
					.append("\n修改对象"+conditionTSysUserPO.getUserId())
					.append("\n修改内容："+valueTSysUserPO.toXMLStringBuffer().toString());
				logger.info(info.toString());
			}
		}
	}
	
	/**
	 * 删除用户信息
	 * @param atx
	 * @param userid
	 * @throws Exception
	 */
	public static void deleteUserByPK(ActionContext atx, Integer userid) throws Exception{
		String updateBy = SystemUtils.getSessionUser(atx);
		Connection con = atx.getConection();
		if(updateBy.equals(userid.toString())){
			UserOperationException uoe = new UserOperationException();
			atx.setErrorContext("FSTI_SYS_USER_1006", MessageService.getMessage("FSTI_SYS_USER_1006"), uoe);
			throw uoe;
		}
		TUserPO tUserPO = new TUserPO();
		tUserPO.setUserId(userid);
		POUtils.delete(con, tUserPO);
		//日志
		StringBuffer info = new StringBuffer();
		info.append("\n【删除用户】")
			.append("\nIP："+atx.getRemoteAddr())
			.append("\n操作用户ID："+atx.getSessionValue(Constant.SESSION_USER_NO).toString())
			.append("\n删除对象"+tUserPO.getUserId());
		logger.info(info.toString());
	}
	
	/**
	 * 批量删除用户信息
	 * @param atx
	 * @param userid
	 * @throws Exception
	 */
	public static void batchDeleteUserByPK(ActionContext atx, Integer[] userids) throws Exception{
		if(userids!=null){
			String updateBy = SystemUtils.getSessionUser(atx);
			UserOperationException uoe = new UserOperationException();
			StringBuffer logPkUser = new StringBuffer();
			for (Integer userid : userids) {
				if(updateBy.equals(userid.toString())){
					atx.setErrorContext("FSTI_SYS_USER_1006", MessageService.getMessage("FSTI_SYS_USER_1006"), uoe);
					throw uoe;
				}
				if(userid == Constant.ADMIN_NO){
					atx.setErrorContext("FSTI_SYS_USER_1007", MessageService.getMessage("FSTI_SYS_USER_1007"), uoe);
					throw uoe;
				}
				logPkUser.append(userid).append(";");
				TUserPO tUserPO = new TUserPO();
				tUserPO.setUserId(userid);
				POUtils.delete(atx.getConection(), tUserPO);
			}
			
			//日志
			StringBuffer info = new StringBuffer();
			info.append("\n【批量删除用户】")
				.append("\nIP："+atx.getRemoteAddr())
				.append("\n操作用户ID："+atx.getSessionValue(Constant.SESSION_USER_NO).toString())
				.append("\n删除对象："+logPkUser.toString());
			logger.info(info.toString());
		}
	}
	
	/**
	 * 根据条件分页查询用户信息
	 * @param atx
	 * @param pager
	 * @param username
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static ComboPager queryUserByPage(ActionContext atx, Pager pager, String loginName, String username, Integer isLock) throws Exception{
		Connection con = atx.getConection();
		ComboPager cp = TSysUserDao.queryTSysUserByPager(con, pager, loginName, username, isLock);
		if(cp != null){
			List list = cp.getRs();
			if(list != null && !list.isEmpty()){
				int size = list.size();
				for(int i = 0; i < size; i++){
					DynaBeanMap dbm = (DynaBeanMap)list.get(i);
					Integer userid = Integer.valueOf(dbm.get("USER_ID").toString());
					List rolenameList = TSysUserDao.queryUserRoleList(con, userid);
					StringBuffer rsb = new StringBuffer();
					if(rolenameList != null && !rolenameList.isEmpty()){
						int rolenameSize = rolenameList.size();
						for(int j = 0; j < rolenameSize; j++){
							DynaBeanMap roleDbm = (DynaBeanMap)rolenameList.get(j);
							rsb.append(roleDbm.get("ROLE_NAME").toString());
							if(j != rolenameSize - 1){
								rsb.append(",");
							}
						}
					}
					dbm.put("ROLE_NAME", rsb.toString());
				}
			}
		}
		return cp;
	}
	
	/**
	 * 查看单个用户信息
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static DynaBeanMap getUserByPK(ActionContext atx, Integer userid) throws Exception{
		Connection con = atx.getConection();
		DynaBeanMap dbm = TSysUserDao.getTSysUserByPk(con,userid);
		return dbm;
	}
	
	/**
	 * 重置密码
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	public static void resetUserPWDByPK(ActionContext atx, Integer userid) throws Exception{
		SystemUtils.getSessionUser(atx);
		TUserPO conditionTSysUserPO = new TUserPO();
		TUserPO valueTSysUserPO = new TUserPO();
		conditionTSysUserPO.setUserId(userid);
		valueTSysUserPO.setPassword(Constant.DEFAULT_PASSWORD);
		POUtils.update(atx.getConection(), conditionTSysUserPO, valueTSysUserPO, false);
		//日志
		StringBuffer info = new StringBuffer();
		info.append("\n【重置用户密码】")
			.append("\nIP："+atx.getRemoteAddr())
			.append("\n操作用户ID："+atx.getSessionValue(Constant.SESSION_USER_NO).toString())
			.append("\n修改对象"+conditionTSysUserPO.getUserId())
			.append("\n修改内容："+valueTSysUserPO.toXMLStringBuffer().toString());
		logger.info(info.toString());
	}
	
	/**
	 * 锁定/解锁账号
	 * @param atx
	 * @param userid
	 * @param islock
	 * @return
	 * @throws Exception
	 */
	public static void lockUserByPK(ActionContext atx, Integer userid, Integer islock) throws Exception{
		SystemUtils.getSessionUser(atx);
		TUserPO conditionTSysUserPO = new TUserPO();
		TUserPO valueTSysUserPO = new TUserPO();
		conditionTSysUserPO.setUserId(userid);
		if(islock.equals(Constant.IS_LOCKED_FALSE)){
			valueTSysUserPO.setIsLock(Constant.IS_LOCKED_TRUE);
		}
		else{
			valueTSysUserPO.setIsLock(Constant.IS_LOCKED_FALSE);
		}
		POUtils.update(atx.getConection(), conditionTSysUserPO, valueTSysUserPO, false);
		//日志
		StringBuffer info = new StringBuffer();
		info.append("\n【锁定/解锁用户】")
			.append("\nIP："+atx.getRemoteAddr())
			.append("\n操作用户ID："+atx.getSessionValue(Constant.SESSION_USER_NO).toString())
			.append("\n修改对象"+conditionTSysUserPO.getUserId())
			.append("\n修改内容："+valueTSysUserPO.toXMLStringBuffer().toString());
		logger.info(info.toString());
	}
	
}
